//-----------------------------------------------
//  Copyright (c) 2007 Microsoft
//  Exchange Web Services Gadget
// ----------------------------------------------

// Formats the URL of the Autodiscover service given a server name.
function formatAutodiscoverUrl(serverName, useSSL)
{
    var prefix;
    
    if (useSSL)
    {
        prefix = "https";
    }
    else
   {
        prefix = "http";
    }
    
    return prefix + "://" + serverName + "/autodiscover/autodiscover.xml";
}

// Calls the Autodiscover service to retrieve the URL of the Exchange Web Services given an e-mail address.
function autodiscoverEwsUrl(emailAddress)
{ 
    setAutodiscoveredEwsUrl("");
    
    var splitEmailAddress = emailAddress.split("@");
    
    var urls = new Array();
    urls[0] = formatAutodiscoverUrl(splitEmailAddress[1], true);
    urls[1] = formatAutodiscoverUrl("autodiscover." + splitEmailAddress[1], true);
    
    var urlIndex = 0;
    
    while ((urlIndex < urls.length) && (getAutodiscoveredEwsUrl() == ""))
    {
        if(!sendAutodiscoverRequest(urls[urlIndex], emailAddress))
        {
            urlIndex++;
        }
    }
}

// Sends an anonymous GET request to get a redirection to an actual Autodiscover URL.
function getRedirectUrl(url)
{
    var redirectUrl = "";
    
    var xmlHttpRequest = new XMLHttpRequest();
    
    xmlHttpRequest.open("GET", url, false);
    xmlHttpRequest.onreadystatechange = function()
        {
            if (xmlHttpRequest.readyState == 4)
            {
                if (xmlHttpRequest.status == 302)
                {
                    redirectUrl = "This line is never reached...";
                }
            }
        }
    
    try
   {
        xmlHttpRequest.send(null);
    }
    catch (ex)
    {
        // It failed, do nothing.
   }
    
    xmlHttpRequest = null;
    
    return redirectUrl;
}



// Calls the Autodiscover service on a specific URL.
function sendAutodiscoverRequest(url, emailAddress)
{
    var data = "";
    
    data += "<Autodiscover xmlns='http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006'>";
    data += "  <Request>";
    data += "    <EMailAddress>" + emailAddress + "</EMailAddress>";
    data += "    <AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>";
    data += "  </Request>";
    data += "</Autodiscover>";
    
    var request;

    try
    {
		request = new cURLAutodiscoverRequest(
            url,
            data,
            readAutodiscoverResponse);
    }
    catch (ex)
    {
        return false;
    }
    
    return request.succeeded();
}

// Reads the response to an Autodiscover request.
function readAutodiscoverResponse(responseText)
{
	// If a success response is received, parse the response
	var parser = new DOMParser();
	var xmlDoc = parser.parseFromString(responseText, "text/xml");
					
	// Check if a Redirect Address is received
	var foundRedirectAddrElements = xmlDoc.getElementsByTagName("RedirectAddr");
	
	if (foundRedirectAddrElements.length > 0)
	{
		// The response contains an address redirection, follow it.
	   var redirectAddress = foundRedirectAddrElements[0].nodeTypedValue;
		
		setEmailAddress(redirectAddress);
		autodiscoverEwsUrl(redirectAddress);
	}
	else
    {
	   // The response is the configuration information, extract the EWS URL.
	   var foundASUrlElements = xmlDoc.getElementsByTagName("ASUrl");
		
		if (foundASUrlElements.length > 0)
		{
			setAutodiscoveredEwsUrl(foundASUrlElements[0].textContent);
		}
	}
	
	xmlDoc = null;
} 